package com.zp.qualitypractice.io;

import android.content.Context;

import com.zp.qualitypractice.App;
import com.zp.qualitypractice.FileUtils;
import com.zp.qualitypractice.PhoneStateUtils;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by izp on 2017/4/14.
 */

public class RetrofitHelper {
    private static RetrofitHelper sInstance;
    private OkHttpClient mOkHttpClient = null;
    private final String NETWORK_CACHE_DIR = "NetCache";
    private final String BASEURL = "http://api.yourapplication.com/";

    private RetrofitHelper(){
    }

    public static RetrofitHelper getInstance(){
        return InstanceHolder.sRetrofitHelper;
    }
    private static class InstanceHolder {
        static RetrofitHelper sRetrofitHelper = new RetrofitHelper();
    }

    private OkHttpClient getClient(final Context context){
        if (null==mOkHttpClient){
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            File cacheFile = new File(FileUtils.getNetCacheDir(App.getApp(),NETWORK_CACHE_DIR));
            Cache cache = new Cache(cacheFile,1024*1024*50);//50m
            Interceptor cacheInterceptor = new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request();
                    if (!PhoneStateUtils.isNetworkConnected(context)){//网络不可用
                        request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
                    }
                    Response response = chain.proceed(request);
                    if (PhoneStateUtils.isNetworkConnected(context)){
                        int maxAge = 0;
                        // 有网络时, 不缓存, 最大保存时长为0
                        response.newBuilder().header("Cache-Control", "public, max-age=" + maxAge)
                                .removeHeader("Pragma")
                                .build();
                    }else {
                        // 无网络时，设置超时为4周
                        int maxStale = 60 * 60 * 24 * 28;
                        response.newBuilder()
                                .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                                .removeHeader("Pragma")
                                .build();
                    }
                    return response;
                }
            };
            //设置缓存
            builder.addNetworkInterceptor(cacheInterceptor);
            builder.addInterceptor(cacheInterceptor);
            builder.cache(cache);
            //设置超时
            builder.connectTimeout(10, TimeUnit.SECONDS);
            builder.readTimeout(20, TimeUnit.SECONDS);
            builder.writeTimeout(20, TimeUnit.SECONDS);
            //错误重连
            builder.retryOnConnectionFailure(true);
            mOkHttpClient = builder.build();
        }
        return mOkHttpClient;
    }

    /**
     * 添加头部
     *
     * @param request
     * @return
     */
    private Request addHeaders(Request request) {
        Request.Builder builder = request.newBuilder();

        builder.addHeader("Connection", "Keep-Alive")
                .addHeader("Cache-Control", "no-cache")
                .addHeader("Accept-Language", "zh-CN,en-US");
        return builder.build();
    }

    public  <T> T getApiService(String baseUrl, Class<T> clz) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(getClient(App.getApp()))
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        return retrofit.create(clz);
    }

    public Apis.Splash getSplash(){
        return getApiService(BASEURL, Apis.Splash.class);
    }
}
